import { base64ToFile } from './util';
import { uploadFileWithFormData } from '../api/api';

/** 上传图片到服务器 */
export const uploadBase64Image = async base64 => {
	let formData = new FormData();
	let fileFormat = 'png';
	let blob = base64ToFile(base64, fileFormat);
	formData.append('file', blob, fileFormat);
	console.log(blob, blob.size);
	try {
		let { data } = await uploadFileWithFormData(formData);
		return { url: data.data.url, size: blob.size, name: data.data.originalname };
	} catch (e) {
		return null;
	}
};

/** 上传文件到服务器 */
export const uploadFile = async file => {
	let formData = new FormData();
	formData.append('file', file);
	try {
		let { data } = await uploadFileWithFormData(formData);
		return { url: data.data.url, size: file.size, name: file.name, suffix: getFileSuffix(file.name) };
	} catch (e) {
		return null;
	}
};

/** 获取文件后缀名 */
export const getFileSuffix = name => {
	return name.substring(name.lastIndexOf('.') + 1);
};

/** 计算文件大小 */
export const getFileSize = size => {
	let count = 0;
	let total = size / 1024;
	let result = '';
	while (total > 1024) {
		total = total / 1024;
		count++;
	}
	switch (count) {
		case 0:
			result = total.toFixed(2) + 'KB';
			break;
		case 1:
			result = total.toFixed(2) + 'MB';
			break;
		case 2:
			result = total.toFixed(2) + 'G';
			break;
		case 3:
			result = total.toFixed(2) + 'T';
			break;
		default:
			break;
	}
	return result;
};
